package org.popupcommunication.controller;


import java.beans.PropertyEditorSupport;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
import java.util.Map;

import javax.validation.Valid;

import org.popupcommunication.dao.GroupDAO;
import org.popupcommunication.model.AgendaGroupe;
import org.popupcommunication.model.Group;
import org.popupcommunication.model.MyFiles;
import org.popupcommunication.service.GroupManager;
import org.popupcommunication.utils.FileUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

@Controller
@RequestMapping("admin/fichiers")
public class AdminFilesController {
	@Autowired
	GroupManager groupService;	
	@Autowired
	GroupDAO groupRepository;
	
	List<Group> lstGrp;
	Map<Integer, Group> groupeCache;
	private static final String form_ajout = "fichiers/ajoutFichier";
	private static final String confirmation = "fichiers/confirmation";

	@InitBinder
	public void initBinder(WebDataBinder binder) {
		binder.setAllowedFields(new String[] {  "fich",
				 "groupe","fileupload" });

		binder.registerCustomEditor(Group.class, "groupe",
				new PropertyEditorSupport() {
					@Override
					public void setAsText(String id) {
						Group gg = groupRepository.findById(Integer.valueOf(id));
						setValue(gg);
					}
				});
	}	
	@RequestMapping(value = "new", method = RequestMethod.GET)
	public String showForm(Model model) {
		lstGrp = groupService.getAllGroups();
		model.addAttribute("lstGroupes", lstGrp);
		model.addAttribute("fichier", new MyFiles());
		return form_ajout;
	}
	

	@RequestMapping("/fileUpload")  
	 public @ResponseBody ModelAndView fileUploaded(MultipartHttpServletRequest request,  
			 @RequestParam("grp") String grp,
	            @RequestParam("file") MultipartFile file) {  
		System.out.println(file.getOriginalFilename());
	  InputStream inputStream = null;  
	  OutputStream outputStream = null;  
	  String fileFolder = null;
	  System.out.println("groupe "+grp);

	  fileFolder = request.getSession().getServletContext().getRealPath("/resources/upload/group/"+grp +"/");
	 // fileValidator.validate(uploadedFile, result);  
	  
	  String fileName = file.getOriginalFilename();  

	  try {  

	   File path = new File(fileFolder);
	   File newFile = new File(fileFolder +"/" + fileName);  

	   if(!path.exists() ){
		   path.mkdirs();
	   }
	   if (!newFile.exists()) {  
	    newFile.createNewFile();  
	   }  
	   outputStream = new FileOutputStream(newFile);  
	   outputStream.write(file.getBytes());
	  } catch (IOException e) {  

	   e.printStackTrace();  
	  }  
	  finally{
		  try {
			outputStream.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	  }
	  return new ModelAndView(confirmation, "message", fileName);  
	 }  
}
